﻿using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace Bongiozzo
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }

    public class LocalizationAwareAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var httpContext = filterContext.HttpContext;
            string language = "en";
            HttpCookie langCookie = httpContext.Request.Cookies["lang"];

            if (langCookie == null)
            {
                if (httpContext.Request.UserLanguages != null &&
                    httpContext.Request.UserLanguages[0].IndexOf("ru", StringComparison.OrdinalIgnoreCase) != -1)
                    language = "ru";

                httpContext.Response.AppendCookie(createCookie(language));
            }
            else
                if (langCookie.Value == "ru")
                    language = "ru";

            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
        }

        public static HttpCookie createCookie(string language)
        {
            HttpCookie cookie = new HttpCookie("lang", language);
            cookie.Expires = DateTime.Now.AddYears(1);
            return cookie;
        }
    }
}